<template>
    <div class="Bulletin">      
      <el-text><el-icon size="12"><WarningFilled /></el-icon>{{ state.bulletinFirst.content }}</el-text>      
    </div>
   <div class="filter">
      <el-form
      ref="filterInformation"
      :model="state.filterInformation"    
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
        <el-form-item label="等级" prop="grade">
          <el-radio-group v-model="state.filterInformation.grade" @change="getPaperByFilter">
            <el-radio label="all" >全部</el-radio>
            <el-radio label="七年级" >七年级</el-radio>
            <el-radio label="八年级">八年级</el-radio>
            <el-radio label="九年级">九年级</el-radio>
            <el-radio label="中考">中考</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="阶段" prop="stage">
          <el-radio-group v-model="state.filterInformation.stage" @change="getPaperByFilter">
            <el-radio label="all" >全部</el-radio>
            <el-radio label="联考" >联考</el-radio>
            <el-radio label="期中">期中</el-radio>
            <el-radio label="期末">期末</el-radio>
            <el-radio label="模">中考模考</el-radio>
            <el-radio label="真题">中考真题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-radio-group v-model="state.filterInformation.year"  @change="getPaperByFilter">
            <el-radio label="all" >全部</el-radio>
            <el-radio :label="item" v-for="item in getYearList" :key="item" >{{ item }}</el-radio>       
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-radio-group v-model="state.filterInformation.order" @change="getPaperByFilter">
            <el-radio label="all" >默认</el-radio>
            <el-radio label="-publish_time" >新→旧</el-radio>
            <el-radio label="publish_time">旧→新</el-radio>
          </el-radio-group>
        </el-form-item>    
        <el-form-item label="搜索" prop="key_words">
          <el-input
            v-model="state.filterInformation.key_words"
            style="max-width: 400px"
            placeholder="请输入关键词"
            class="input-with-select"
          >
            <template #append>
              <el-button :icon="Search" @click="getPaperByFilter(true)" />
            </template>
          </el-input> 
        </el-form-item>
      </el-form>
    </div>
  <div class="showQuestion">  
   
    <!-- 用卡片展示试卷 -->
    <div  class="questionsBody" id="questionsBodyRef" ></div>
    <el-table class="tableClass" :data="state.paperList" stripe                   
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"                    
        border
    > 
        <el-table-column type="index" width="45" label="序" />
        <el-table-column align="center" width="550"  label="标题" >
          <template #default="scope">
            <div class="operate">
              <el-button text size="large" @click="gotoShowQuestion(scope.row.id)" :type="getButtonType(scope.row.id)">{{ scope.row.title }}</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="110" label="操作" >                  
            <template #default="scope">
              <div class="operate">                
                <el-button text type="success" v-if="scope.row.file!=''" @click="onClickDownloadFile(scope.row.id)">下载</el-button>
                <el-button text type="primary" @click="onClickUpload(scope.row,scope.row.id)"  v-else>上传</el-button>                  
                <el-button text type="warning" v-if="scope.row.file!=''" @click="onClickViewFile(scope.row.file)">预览</el-button>        
              </div>
            </template>
        </el-table-column>
    </el-table>
      <!-- 分页展示题目 -->
      <div class="pagination">        
        <el-pagination
          background
          layout="total, pre, pager, next"
          :total="state.total"
          :page-size="state.size"
          @current-change="handleCurrentChangeFilter" 
        />     
      </div>
  </div>  
</template>

<script setup>
  import { reactive, ref, onMounted, computed, getCurrentInstance } from 'vue'
  import axios from '@/utils/axios'
  import { useRoute, useRouter } from 'vue-router'
  import {WarningFilled,Search} from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { useStore } from 'vuex'
  import { localGet, localSet, uploadPaperFileServer, deepClone} from '@/utils'
  import config from '~/config'
  import { Base64 } from 'js-base64';

  // 点击试卷，跳转到试题展示页面
  const gotoShowQuestion=(id)=>{
    router.push({path:'/getQuestionsByPaper', query:{ id: id, page: 1, size:10}})
  }
  // 新窗口预览原式试卷
  const onClickViewFile = ()=>{
    file = config[import.meta.env.MODE].baseUrl_noapi + file
    // console.log("file", file)
    window.open(onlinePreview + encodeURIComponent(Base64.encode(file)));
  }
  const buttonTypeList = ['primary', 'success', 'info', 'warning', 'danger']
  const getButtonType =(value)=>{
    // console.log('value', value)
    return buttonTypeList[value % buttonTypeList.length]
  }
  // 4个选项的筛选试题
  const getPaperByFilter = (has_keyword=false) =>{
    state.getQuestionByFilter = true
    let params = deepClone(state.filterInformation)
    params['page'] = state.page
    params['size'] = state.size
    if(has_keyword==false){
      params['key_words'] = ''
    }
    console.log('params:', params)
    axios.get('/PaperModelViewSet/get_paper_by_filter/',{params}).then(res => {
      if (res.code==200){
        console.log("筛选得到试卷：",res)
        state.paperList = res.data.results
        for(let index=0; index<state.questionList.length;index++ ){
          state.questionList[index].content = modifyDoubleDollarToSingle(state.questionList[index].content)
        }
        console.log('修改后的列表试题：', state.questionList)
        state.total=res.total
        // scrollToTop()
      }else{
        ElMessage("获取试卷失败")
        console.log("获取题目失败：",res)
        state.total=0
        state.error = res.message
        if (res.code==403){
          ElMessage.error("请重新登录")
          router.push("/login")
        }
      }
    })
    .catch((error)=>{
      console.log("获取目录题目错误：", error)
    })
    state.filterInformation.key_words=''
  }
    // 把双$符号改成单$符号
    const modifyDoubleDollarToSingle=(content_str) =>{
    while(content_str.includes('$$')){
      content_str = content_str.replace('$$', '$');
    }
    while(content_str.includes('\\\\')){
      content_str = content_str.replace('\\\\', '\\');
    }
    return content_str
  }
  const formSize = ref('default')
  // 通过结构，获得appContext变量
  const { appContext } = getCurrentInstance()
  // 获得全局上下文后， 得到$bus事件总线
  const eventBus = appContext.config.globalProperties.$bus
  // （发布）触发本注册的事件:即清空tree组件选中复选框状态  
  const store=useStore()
  const route = useRoute()
  const router = useRouter()
  const state = reactive({
    filterInformation: {
      grade: 'all',
      stage: 'all',
      year: 'all',
      key_words: '',
      order: 'all',
    },
    paperList: [],
    file: '',      //存放按试卷查找的试卷url
    bulletinList: [],   //公告栏通知
    bulletinFirst: {},   // 公告栏第一条通知
    fileList:[],
    id: 0,          // 存储册、章、节、知识点的id，默认的第一册
    page: 1,
    size: 10,
    loading: false, // 列表数据接口返回前的 loading
    questionList: [], // 数据列表
    total: 0, // 总条数
    currentPage: 1, // 当前页
    pageSize: 10, // 分页大小
    knowledgepointId: -1,
    apiName : "/questions/catalogue/",    //后端api名称
    range: "course",      //所有题目的大范围，比如按章、节、课程等
    isGetQuestionsByKnowledgepoint: false,  //是否按照知识点搜索题目，方便判断录入题目
    isgetQuestionsByPaper:false,    //是否联考试题页面，用于新增该联考卷
    paperId:10,                      // 当前页面卷子的id
    selectQuestionList: [],         // 选中的题目，用于组卷
    question: null,
    question_detail: Object,
    type: "modifySelectedQuestion",
    userFavoriteQuestions:[],
    drawer:false,
    token:localGet('token') || "",
    uploadPaperFileServer,
    limit:3,
    questionListUploading:[],       // 将要上传给试卷的题目列表
    showQuestionList:[],            // 用于查看的题目
    secondDrawer:false,              //第2个抽屉的显示
    thirdDrawer:false,              // 第3个抽屉的显示
  })
  // 下载试卷pdf
  const onClickDownloadFile = (file) =>{   
    //点击链接
    const link = document.createElement('a');
    link.href = file;
    link.setAttribute('download', 'download.pdf');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link)
  }

const TypeSet = async function (elements) {
  if (!window.MathJax) {
      return
  }
  window.MathJax.startup.promise = window.MathJax.startup.promise
      .then(() => {
          return window.MathJax.typesetPromise(elements)
      })
      .catch((err) => console.log('Typeset failed: ' + err.message))
  return window.MathJax.startup.promise
}
onMounted(()=>{
  getBulletin()
  getPaperByFilter()
})

  // 获取通告栏内容
  const getBulletin = () => {
    const getBulletinCache = localGet('getBulletinCache')
    const getBulletinCacheStartTime = localGet('getBulletinCacheStartTime')
    console.log('getBulletinCache:', getBulletinCache)
    console.log('getBulletinCacheStartTime:', getBulletinCacheStartTime)
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear()
    const currentMonth = currentDate.getMonth() + 1
    const currentDay = currentDate.getDate()
    const currentTime = currentYear*10000 + currentMonth * 100 + currentDay
    if(getBulletinCache!=undefined && getBulletinCacheStartTime!=undefined && getBulletinCacheStartTime>20240000){   
        const dateDiff = currentTime - getBulletinCacheStartTime
        if(dateDiff <=1){
          if(getBulletinCache!=[]){
            console.log('从缓存恢复公告栏')
            state.bulletinList = getBulletinCache
            state.bulletinFirst = state.bulletinList[state.bulletinList.length -1]
            return 1
          }
        } 
    }
    axios.get('/BulletinModelViewSet/get_bulletin').then(res => {
      if (res.code==200){
        // console.log("后台获取公告栏",res)
        state.bulletinList = res.data.results
        state.bulletinFirst = state.bulletinList[state.bulletinList.length -1]
        localSet('getBulletinCache', res.data.results)
        localSet('getBulletinCacheStartTime', currentTime)
      }else{
        console.log("获取公告栏失败：",res)
      }
    })
    .catch((error)=>{
      console.log("获取公告栏错误：", error)
    })   
  }

   //点击页码时触发
  const handleCurrentChangeFilter = (current_page)=>{
    state.page = current_page
    getPaperByFilter()
  }
  // 获取当前路由名
  const currentRouteName = computed(()=>route.path.split('/').pop())
  function fillArray(a, b) {
    let result = [];
    for (let i = a; i <= b; i++) {
        result.push(i);
    }
    return result;
}
  // 获取当前年份，并组成年份数组，从2024年开始,并转换为字符串
  const getYearList = computed(()=>fillArray(2024,new Date().getFullYear()).map(String))
 
</script>
<style scoped>
html, body {
	width: 100%;
	height: 100%;
}
.showQuestion{
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: flex-end;
  font-size: 12px;
  margin: 1;
  padding: 1;
}
  .card-header {
    display: flex;
    justify-content:flex-end;
    align-items: flex-start;
    flex-flow: row nowrap;
    font-size: 12px;
    margin: 0;
    padding: 0;
    height: 20px;
  }
  .question-knowledge{
    display: flex;
    flex-flow: row wrap;
    justify-content: space-between;
    align-items: flex-start;
    /* margin: 2rpx; */
  }
  .others{
    /* margin: 2rpx; */
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-end;
    align-items: center;
  }
  .card_content {
    display: flex;
    flex-flow: column wrap;
    margin: 0px;
    padding: 0px;
  }
  .text {
    font-size: 12px;
  }
  .item {
    margin-bottom: 1px;
  }
  .box-card {
    display: flex;
    flex-flow: column wrap;
    align-items: stretch;
    height: auto;
    width: 100%;
    overflow-y: auto;
  }
  .line-break{
  white-space: pre-wrap;
  width: 950px;
  font-size: 16px;
  }
  img{
      display:block;
  }
  .affix-container{
    text-align: right;
    margin: 0 20px 0 0;
  }
  
.tableClass .cell{   
    padding: 0!important;
    height: 20px!important;
    line-height: 20px!important;
    text-align: center;
    font-size: 10px;
  }
  .tableButton{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  .questionsBody{
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    align-items: stretch;
    overflow-y: auto;
    margin: 0;
    padding: 0;
  }
  .addOneQuestionButton{
    margin: 0;
    padding: 0;
  }
  .pagination{
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
  }
  /* .operateButton{
    padding: 0;
    margin: 0;
    display: flex;
    flex-flow: row nowrap;
  } */
  .linkKnowledgepoint{
    display: flex;
    flex-flow: row nowrap;
  }
  .Bulletin {
    width: 450px;
    margin: 0;
    padding: 0;
    height: 22px;
    font-size: xx-small;
    white-space: nowrap;
    animation: scroll 10s linear infinite;
  }
  @keyframes scroll {
  0% { transform: translateX(100%); }
  100% { transform: translateX(-100%); }
}
/*
user-select: auto|none|text|all;
auto	默认。如果浏览器允许，则可以选择文本。
none	防止文本选取。
text	文本可被用户选取。
all	    单击选取文本，而不是双击。
*/
*{
user-select:none;
}

.prohibitSel{
user-select:none;
}
.filter {
  margin: 5px;
  padding: 3px;
}
</style>